﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("SysPayment")]
	public class SysPaymentController : BaseDbController
	{
		public ActionResult Index()
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			return View();
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, SysPaymentModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = DbContext.SysPaymentMaster.AsNoTracking().Where(x => !string.IsNullOrEmpty(x.Status));
			if (!string.IsNullOrWhiteSpace(model.SelPaidType))
			{
				sql = sql.Where(x => x.PaymentName.Contains(model.SelPaidType));
			}
			int total = await sql.CountAsync();

			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.Sort).ThenByDescending(x => x.UpdateDate).ThenBy(x => x.PaymentName).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();

			var result = sqlResult.Select(x => new
			{
				ID = x.ID,
				PaymentName = LoginUser.Language == ConstValues.Language.Cn ? x.PaymentName : x.PaymentNameEn,
				IsOnline = x.IsOnline,
				Status = x.Status,
				Sort = x.Sort,
				Remark = x.Remark,
				Creator = x.Creator,
				CreateIP = x.CreateIP,
				CreateDate = LoginUser.Language == ConstValues.Language.Cn ?
					x.CreateDate.Value.ToString("yyyy-MM-dd") :
					x.CreateDate.Value.ToString("MM/dd/yyyy")
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			}
			, JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetEditData(string id)
		{
			var data = await DbContext.SysPaymentMaster.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);
			if (data != null)
			{
				var result = new
				{
					id = data.ID,
					paymentName = data.PaymentName,
					PaymentNameEn = data.PaymentNameEn,
					isOnline = data.IsOnline == true ? ConstValues.GenericSelectionType.有 : ConstValues.GenericSelectionType.无,
					sort = data.Sort,
					status = data.Status,
					remark = data.Remark
				};
				return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
					JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
					JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> Delete(SysPaymentModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var exist = await DbContext.ConferencePaymentMaster.AsNoTracking()
					.Where(x => x.PayId == model.Id).ToListAsync();
			if (exist.Count > 0)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgUsingCanNotDelete),
						JsonRequestBehavior.AllowGet);
			}
			var pay = await DbContext.SysPaymentMaster.FirstOrDefaultAsync(x => x.ID == model.Id);
			if (pay != null)
			{
				DbContext.SysPaymentMaster.Remove(pay);

				await DbContext.SaveChangesAsync();

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessDelete),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> Create(SysPaymentModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var result = await DbContext.SysPaymentMaster
				    .FirstOrDefaultAsync(x => x.PaymentName == model.paidType || x.PaymentNameEn == model.paidTypeEn);
			if (result != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(
					string.Format(Resources.MsgRecordExist, Resources.Name)),
					JsonRequestBehavior.AllowGet);
			}
			var payment = new SysPaymentMaster
			{
				ID = Utility.GetTableId(ConstValues.TableName.SysPaymentMaster),
				PaymentName = model.paidType,
				PaymentNameEn = model.paidTypeEn,
				IsOnline = model.isOnLinePay,
				Status = model.Status,
				Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort,
				Remark = model.Remark?.Trim(),
				Creator = LoginUser.UserName,
				CreateIP = LoginUser.IP,
				CreateDate = DateTime.Now
			};

			DbContext.SysPaymentMaster.Add(payment);
			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> Modify(SysPaymentModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);
			var mail = await DbContext.SysPaymentMaster.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (mail != null)
			{
				var modifyData = await DbContext.SysPaymentMaster.FirstOrDefaultAsync(x => x.PaymentName == model.paidType && x.ID != model.Id);
				if (modifyData != null)
				{
					return JsonCamelCase(Utility.CreateFailJsonResult(
						string.Format(Resources.MsgRecordExist, Resources.PaymentType)),
						JsonRequestBehavior.AllowGet);
				}
				mail.PaymentName = model.paidType;
				mail.IsOnline = model.isOnLinePay;
				mail.Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort;
				mail.Remark = model.Remark?.Trim();
				mail.Status = model.Status;
				mail.PaymentNameEn = model.paidTypeEn;
				mail.Updater = LoginUser.UserName;
				mail.UpdateDate = DateTime.Now;
				mail.UpdateIP = LoginUser.IP;

				await DbContext.SaveChangesAsync();

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit), JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist)
									, JsonRequestBehavior.AllowGet);
			}
		}
	}
}